package com.house.controller;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.house.common.Result;
import com.house.entity.Image;
import com.house.service.ImageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;


/**
 * 上传控制层
 */
@RestController
@RequestMapping("upload")
@Slf4j
public class UploadController {


    /**
     * 本地上传地址
     */
    @Value("${local.upload.path}")
    private String LOCAL_UPLOAD_PATH;

    @Autowired
    private ImageService imageService;


    /**
     * 单图片上传
     * @param file
     * @return
     */
    @PostMapping("/singleImageUpload")
    public Result singleImageUpload(@RequestParam("uploadImage") MultipartFile file) {

        try {
            //判断上传文件格式
            String fileType = file.getContentType();

            // 要上传的目标文件存放的绝对路径
            final String localPath = LOCAL_UPLOAD_PATH + "image";

            //上传后保存的文件名(需要防止图片重名导致的文件覆盖)
            //获取文件名
            String fileName = file.getOriginalFilename();

            //获取文件后缀名
            String suffixName = fileName.substring(fileName.lastIndexOf("."));

            //重新生成文件名
            fileName = System.currentTimeMillis() + suffixName;
            File f = FileUtil.writeBytes(file.getBytes(), localPath + "//" + fileName);

//            Image image = new Image();
//            image.setImg(fileName);
//            image.setCreateTime(DateUtil.now());
//            image.setUpdateTime(DateUtil.now());
//            imageService.save(image);

            return Result.ok(f.getName());
        } catch (Exception e) {
            log.error("图片上传失败 cause: {}", e.getMessage());
            e.printStackTrace();
            return Result.error("图片上传失败");
        }
    }


    /**
     * 删除图片
     * @param img
     * @return
     */
    @PostMapping("/deleteImage")
    public Result deleteImage(@RequestParam("img") String img) {

        imageService.remove(Wrappers.<Image>query().eq("img", img));

        return Result.ok();
    }
}
